package com.jmlee.controller;


import com.jmlee.pojo.Admin;
import com.jmlee.pojo.CommonResult;
import com.jmlee.pojo.PageBean;
import com.jmlee.pojo.Role;
import com.jmlee.service.AdminService;
import com.jmlee.service.RoleService;
import com.jmlee.util.DesensitizationUtil;
import com.jmlee.util.JSONUtil;
import com.jmlee.util.SecurityUtil;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description 处理后台人员的信息
 * @Author jmLee
 * @Date 2021/3/4 23:43
 * @Version 1.0
 */
@Controller
public class AdminController {



    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;
    private Long id;


    @Value("${default.path.upload}")
    private String uploadPath;

    @Value("${default.path.domain}")
    private String domain;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");




    @RequestMapping("/userInfo")
    public ModelAndView seleuserInfo() {
        ModelAndView modelAndView = new ModelAndView("userInfo");

        return modelAndView;
    }

    @RequestMapping("/userInfoList")
    @ResponseBody
    public String userInfoList(Admin admin, HttpServletRequest request, HttpServletResponse response) throws IOException {


        String type = request.getParameter("type");
        String keywords = request.getParameter("keywords");


        if (type != null && !type.equals("")) {
            admin = new Admin();
            if ("userName".equals(type)) {
                admin.setUsername(keywords);
            }

            if ("rolename".equals(type)) {
                admin.setRolename(keywords);
            }
        }
        int curPage = Integer.valueOf(request.getParameter("page"));
        int pageSize = Integer.valueOf(request.getParameter("limit"));



        RowBounds rowBounds = new RowBounds((curPage - 1) * pageSize, pageSize);
        PageBean<Admin> pageBean = new PageBean<>();

        pageBean.setCode(0);
        int count = adminService.selectAdminListCount(admin);


        pageBean.setCount(count);
        pageBean.setData(adminService.selectAdminList(admin, rowBounds));


        String json = JSONUtil.objectToJson(pageBean);

        return json;


    }


    @PostMapping("/checkName")
    @ResponseBody
    public String checkRoleName(@RequestBody Admin admin){

        String username = admin.getUsername();
        Admin admin1 = adminService.checkName(username);
        return null;
    }
    @RequestMapping("/turnuserInfo")
    public String turnuserInfo() {

        return "userInfo";
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @PostMapping("/newUserInfo")
    @ResponseBody
    public CommonResult upload(Admin admin, MultipartFile file) {




        // 比如：/static/upload/2021/03/12/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());
        File folder = new File(uploadPath + format);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        // 对上传的文件重命名，避免文件重名
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径,指定nginx的代理路径
            String filePath = "http://47.99.200.116/" + format + "/" + newName;

//            String username =admin.getUsername();
//
            admin.setIcon(filePath);
//            Admin admin1=adminService.checkName(username);
//            if (admin1 == null){
//                System.out.println("用户名可以注册");
//            SecurityUtil securityUtil =new SecurityUtil();


            admin.setEmail(DesensitizationUtil.commonDisplay(admin.getEmail()));
            admin.setPassword(SecurityUtil.getSha256(admin.getPassword()));
            admin.setMobile(DesensitizationUtil.commonDisplay(admin.getMobile()));
                adminService.addNewUserInfo(admin).toString();
//            }
//            else {
//                System.out.println("用户名已被注册");
//
//            }


        } catch (IOException e) {
            return CommonResult.failed("网络异常");
        }

        return CommonResult.success(admin);
    }


    //      新增人员
    @RequestMapping("/userInfoAdd")
    public ModelAndView UserAdd() {
        ModelAndView modelAndView = new ModelAndView("userInfoAdd");
        return modelAndView;
    }



    //添加
    @RequestMapping("userInfoJson")
    @ResponseBody
    public List<Role> userUpdate(Role role) {
        List<Role> roleInfoList = roleService.getRoleList(role);
        return roleInfoList;
    }

    //获取角色
    @RequestMapping("/userJson")
    @ResponseBody
    public Admin userJson() {
        Admin admin = new Admin();
        Admin admin1 = null;
        admin.setId(id);
        List<Admin> list = adminService.getUserInfoList(admin);
        if (list != null && list.size() == 1) {
            admin1 = list.get(0);
        }
        return admin1;
    }

    /**
     * 修改功能
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/UserInfoSubmit")
    public String updateUserSubmit(@RequestBody Admin admin) {

        adminService.updateAdminSubmit(admin);
        return "userinfoAdd";
    }

    /**
     * 修改菜单的映射
     */
    @RequestMapping("/updateAdmin")
    public String updateAdmin(Long id, Model model) {
        //根据用户的id查询用户信息
        Admin admin = adminService.queryAdminById(id);
        model.addAttribute("admin", admin);

        return "userInfoupda";
    }



    @RequestMapping("/userDelete")
    @ResponseBody
    public String deleteUser(Admin admin) {
        boolean mark = adminService.delete(admin);
        if (mark) {
            return "用户信息删除成功";
        } else {
            return "用户信息删除失败";
        }
    }


}
